<script lang="ts" setup>
import type { HandCardAssetApi } from '#/api/spa/handcard/asset/index';
import type { HandCardType } from '#/api/spa/handcard/type';

import { computed, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import {
  createHandCardAsset,
  getHandCardAsset,
  updateHandCardAsset,
} from '#/api/spa/handcard/asset';
import { getHandCardType } from '#/api/spa/handcard/type';
import { $t } from '#/locales';

import { useFormSchema } from '../data';
import HandCardActionLogForm from './hand-card-action-log-form.vue';
import HandCardUsageForm from './hand-card-usage-form.vue';

const emit = defineEmits(['success']);
/** 子表的表单 */
const subTabsName = ref('handCardUsage');
const handCardUsageFormRef = ref<InstanceType<typeof HandCardUsageForm>>();
const handCardActionLogFormRef =
  ref<InstanceType<typeof HandCardActionLogForm>>();

const formData = ref<HandCardAssetApi.HandCardAsset>();
const getTitle = computed(() => {
  return formData.value?.id
    ? $t('ui.actionTitle.edit', ['手牌资产'])
    : $t('ui.actionTitle.create', ['手牌资产']);
});

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
    formItemClass: 'col-span-2',
    labelWidth: 80,
  },
  layout: 'horizontal',
  schema: useFormSchema(),
  showDefaultActions: false,
});

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    modalApi.lock();
    // 提交表单
    const values = (await formApi.getValues()) as any;
    const data = { ...values } as HandCardAssetApi.HandCardAsset;
    // 拼接子表的数据
    data.handCardUsages = handCardUsageFormRef.value?.getData();
    data.handCardActionLogs = handCardActionLogFormRef.value?.getData();
    // 提交前根据 cardTypeId 查询名称并回填
    if (data.cardTypeId && !data.cardTypeName) {
      try {
        const res: HandCardType = await getHandCardType(data.cardTypeId);
        if (res?.typeName) {
          (data as any).cardTypeName = res.typeName;
        }
      } catch {}
    }
    try {
      await (formData.value?.id
        ? updateHandCardAsset(data)
        : createHandCardAsset(data));
      // 关闭并提示
      await modalApi.close();
      emit('success');
      message.success($t('ui.actionMessage.operationSuccess'));
    } finally {
      modalApi.unlock();
    }
  },
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      return;
    }
    // 加载数据
    let data = modalApi.getData<HandCardAssetApi.HandCardAsset>();
    if (!data) {
      return;
    }
    if (data.id) {
      modalApi.lock();
      try {
        data = await getHandCardAsset(data.id);
      } finally {
        modalApi.unlock();
      }
    }
    // 设置到 values
    formData.value = data;
    await formApi.setValues(formData.value);
  },
});
</script>

<template>
  <Modal :title="getTitle" class="w-2/4">
    <Form class="mx-4" />
    <!--    &lt;!&ndash; 子表的表单 &ndash;&gt;-->
    <!--    <Tabs v-model:active-key="subTabsName">-->
    <!--      <Tabs.TabPane key="handCardUsage" tab="手牌使用记录" force-render>-->
    <!--        <HandCardUsageList ref="handCardUsageFormRef" :card-id="formData?.id"/>-->
    <!--      </Tabs.TabPane>-->
    <!--      <Tabs.TabPane key="handCardActionLog" tab="手牌动作记录表（替换/撤销等）" force-render>-->
    <!--        <HandCardActionLogList ref="handCardActionLogFormRef" :card-id="formData?.id"/>-->
    <!--      </Tabs.TabPane>-->
    <!--    </Tabs>-->
  </Modal>
</template>
